package com.ruoyi.project.im.users.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.IpToAddressUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.im.avatar.domain.VisitorAvatar;
import com.ruoyi.project.im.avatar.service.IVisitorAvatarService;
import com.ruoyi.project.im.bean.IMAuth;
import com.ruoyi.project.im.bean.IMBaseRes;
import com.ruoyi.project.im.code.domain.Code;
import com.ruoyi.project.im.code.domain.UserCode;
import com.ruoyi.project.im.code.service.ICodeService;
import com.ruoyi.project.im.users.domain.Users;
import com.ruoyi.project.im.users.service.IUsersService;
import com.ruoyi.project.im.utils.Http;
import com.ruoyi.project.im.utils.IMManager;
import com.ruoyi.project.im.utils.RandomNum;
import com.ruoyi.project.system.jilu.domain.KamiJilu;
import com.ruoyi.project.system.jilu.service.IKamiJiluService;
import com.ruoyi.project.system.moneydetail.domain.UsersMoneydetail;
import com.ruoyi.project.system.moneydetail.service.IUsersMoneydetailService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 用户管理Controller
 *
 * @author ruoyi
 * @date 2022-08-12
 */
@Controller
@RequestMapping("/im/server")
public class CustomerServerController extends BaseController {
    private String prefix = "im/server";

    @Autowired
    private IUsersService usersService;

    @Autowired
    private ICodeService codeService;

    @Autowired
    private IVisitorAvatarService avatarService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IUsersMoneydetailService usersMoneydetailService;

    @RequiresPermissions("im:users:view")
    @GetMapping()
    public String users() {
        return prefix + "/server";
    }

    /**
     * 查询用户管理列表
     */
    @RequiresPermissions("im:users:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Users users) {
        startPage();
        users.setAppMangerLevel(3);
        User user = getSysUser();//系统用户
        if(user.isAdmin()==false){
            users.setCreateUser(user.getLoginName());
        }
        List<Users> list = usersService.selectUsersList(users);
        return getDataTable(list);
    }


    private VisitorAvatar getAvatar() {
        VisitorAvatar visitorAvatar = avatarService.selectVisitorAvatarById(0L);
        if (visitorAvatar != null) {
            visitorAvatar.setuCount(visitorAvatar.getuCount() + 1);
            avatarService.updateVisitorAvatar(visitorAvatar);
            return visitorAvatar;
        }
        return null;
    }

    /**
     * 导出用户管理列表
     */
    @RequiresPermissions("im:users:export")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Users users) {
        List<Users> list = usersService.selectUsersList(users);
        ExcelUtil<Users> util = new ExcelUtil<Users>(Users.class);
        return util.exportExcel(list, "用户管理数据");
    }

    /**
     * 新增用户管理
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存用户管理
     */
    @RequiresPermissions("im:users:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(UserCode code) {
        Integer num = code.getNum();
        String type = code.getKamitype();
        Long days = (code.getDays());
        String kwz = "";
        String jilu = "";
        if ("uselogin".equals(type)) {
            kwz = "LG";
            jilu = "生成了" + num + "张登录卡密";
        }else{
            return AjaxResult.error();
        }
        User moneyuser = userService.selectUserByLoginName(getLoginName());
        UsersMoneydetail moneydetail = new UsersMoneydetail();
        BigDecimal customeMoney = new BigDecimal(days.intValue() * num * 100); //消费金额
        BigDecimal subMoney = moneyuser.getMoney().subtract(customeMoney); //剩余金额
        if (subMoney.intValue() < 0) {
            return AjaxResult.error("余额不足，请联系管理员充值！");
        }
        int total = 0;
        StringBuilder sb=new StringBuilder();
        for (int i = 0; i < num; i++) {
            String kamicode = RandomNum.randomdaxie(10) + "-" + kwz;
            sb.append(kamicode+"<br>");
            Code code1 = new Code();
            code1.setAddtime(new Date());
            code1.setKamicode(kamicode);
            code1.setIssold("sold");
            code1.setKamistatus("nouse");
            code1.setDays(code.getDays());
            code1.setKamitype(type);
            int f = codeService.insertCode(code1);//添加卡密
            VisitorAvatar visitorAvatar = getAvatar(); //生成用户
            if (visitorAvatar == null) {
                return AjaxResult.error("注册 500");
            }
            String nickname = visitorAvatar.getName();
            String userId = UUID.fastUUID().toString();
            String avatar = visitorAvatar.getAvatar();
            Users users = new Users();
            users.setUserId(userId);
            users.setName(nickname);
            users.setFaceUrl(avatar);
            users.setKamicode(kamicode);
            users.setAppMangerLevel(3);
            users.setActStatus(0);
            users.setCreateUser(getSysUser().getLoginName());

            if(registerUser(userId,nickname,avatar)){
                usersService.updateUsers(users);
                total += f;
            }else {
                return AjaxResult.error("注册用户失败");
            }
        }
        sb.append("登陆卡密");
        if (total == num) {

            moneydetail.setStartMoney(new BigDecimal(String.valueOf(moneyuser.getMoney())));
            moneydetail.setMoney(new BigDecimal(Integer.parseInt(String.valueOf(days)) * num * 100));
            moneydetail.setEndMoney(subMoney);
            moneydetail.setChangeBy(jilu);
            moneydetail.setBeizhu(sb.toString());
            moneydetail.setUserId(moneyuser.getUserId());
            usersMoneydetailService.insertUsersMoneydetail(moneydetail);
            moneyuser.setMoney(subMoney);
            userService.updateUserInfo(moneyuser);

            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }

    }

    private boolean registerUser(String userId,String nickname,String avatar){

        Map<String,Object> map = new HashMap<>();
        map.put("nickname",nickname);
        map.put("faceURL",avatar);
        map.put("platform",5);
        map.put("userID",userId);
        map.put("operationID",IMManager.getOperationID());
        map.put("secret", IMManager.secret);

        String jsonString = JSON.toJSONString(map);
        JSONObject result = Http.post(Http.USER_REGISTER,jsonString);
        IMBaseRes baseRes = result.toJavaObject(IMBaseRes.class);
        JSON json = JSON.parseObject(baseRes.data.toString());
        IMAuth imAuth = json.toJavaObject(IMAuth.class);
        if (!StringUtils.isEmpty(imAuth.token)){
            return true;
        }else {
            return false;
        }

    }


    /**
     * 修改用户管理
     */
    @RequiresPermissions("im:users:edit")
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") String userId, ModelMap mmap) {
        Users users = usersService.selectUsersByUserId(userId);
        mmap.put("users", users);
        return prefix + "/edit";
    }

    /**
     * 修改保存用户管理
     */
    @RequiresPermissions("im:users:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Users users) {
        return toAjax(usersService.updateUsers(users));
    }


    /**
     * 用户续费
     */
    @RequiresPermissions("im:users:edit")
    @GetMapping("/xufei/{userId}")
    public String xufei(@PathVariable("userId") String userId, ModelMap mmap) {
//        Users users = usersService.selectUsersByUserId(userId);
        mmap.put("userId", userId);
        return prefix + "/xufei";
    }

    /**
     * 修改保存用户管理
     */
    @RequiresPermissions("im:users:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/xufei")
    @ResponseBody
    public AjaxResult xufei(String userId, String unit, Integer num) {
        Users users = new Users();
        Users user = usersService.selectUsersByUserId(userId);
        if(user.getActStatus()==0){
            return AjaxResult.error("用户未激活！");
        }
        Date endTime = user.getEndTime();
        Date nowTime = new Date();
        Date startDate;
        if (endTime.getTime() < nowTime.getTime()) {
            startDate = nowTime;
        } else {
            startDate = endTime;
        }
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(startDate);
        users.setUserId(userId);
        int money = 0;
        String unitzn="";
        if ("day".equals(unit)) {
            rightNow.add(Calendar.DATE, num);
            money = 100 * num;
            unitzn="天卡";
        } else if ("week".equals(unit)) {
            rightNow.add(Calendar.WEEK_OF_YEAR, num);
            money = 700 * num;
            unitzn="周卡";
        } else if ("month".equals(unit)) {
            rightNow.add(Calendar.MONTH, num);
            money = 2500 * num;
            unitzn="月卡";
        }

        User usersmoney =userService.selectUserByLoginName(getLoginName());
        BigDecimal customeMoney = new BigDecimal(money); //消费金额
        BigDecimal subMoney = usersmoney.getMoney().subtract(customeMoney); //剩余金额
        if (subMoney.intValue() < 0) {
            return AjaxResult.error("余额不足，请联系管理员充值！");
        }
        users.setEndTime(rightNow.getTime());
        int result = usersService.updateUsers(users);
        if (result > 0) {
            UsersMoneydetail usemoney = new UsersMoneydetail();
            usemoney.setStartMoney(new BigDecimal(String.valueOf(usersmoney.getMoney())));
            usemoney.setMoney(new BigDecimal(money));
            usemoney.setEndMoney(subMoney);
            usemoney.setChangeBy("续费-"+num+"*"+unitzn);
            usemoney.setUserId(usersmoney.getUserId());
            usemoney.setBeizhu(users.getKamicode());
            usersMoneydetailService.insertUsersMoneydetail(usemoney);
            usersmoney.setMoney(subMoney);
            userService.updateUserInfo(usersmoney);
        }
        return toAjax(result);
    }

    /**
     * 删除用户管理
     */
    @RequiresPermissions("im:users:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(usersService.deleteUsersByUserIds(ids));
    }


    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(Users user) {
        return toAjax(usersService.updateUsers(user));
    }


    /**
     * 用户重置密码
     */

    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwd(String userId) {
        Users users = usersService.selectUsersByUserId(userId);
        users.setPassword("123456");
        return toAjax(usersService.updateUsers(users));
    }
}
